package com.jf.blog.util.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("个人博客 API文档")
                .description("后端接口文档")
                .version("V1.0").build();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo).select()
                .apis(RequestHandlerSelectors.basePackage("com.jf.blog.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(newArrayList(
                        new ApiKey("token", "token", "header")
                ))
                .securityContexts(securityContexts());
    }

    private List<SecurityContext> securityContexts() {
        // 1. 创建安全上下文列表
        List<SecurityContext> securityContexts = new ArrayList<>();
        // 2. 添加一个安全上下文配置
        securityContexts.add(SecurityContext.builder()
                // 3. 关联自定义的认证方式（如 Token）
                .securityReferences(defaultAuth())
                // 4. 指定需要应用认证的路径（正则表达式：排除以 "/login和/kaptcha.jpg" 的路径）
                .forPaths(PathSelectors.regex("^(?!/login|/kaptcha.jpg).*$"))
                .build());
        // 5. 返回配置好的安全上下文列表
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        // 1. 创建一个授权范围，描述权限的作用域和描述
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        // 2. 将授权范围放入数组（支持多个范围，但此处仅定义一个）
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        // 3. 创建安全引用列表，用于存储认证方式和授权范围的关联
        List<SecurityReference> securityReferences = new ArrayList<>();
        // 4. 添加一个安全引用，指定使用名为 "token" 的认证方式，并关联授权范围
        securityReferences.add(new SecurityReference("token", authorizationScopes));
        // 5. 返回配置好的安全引用列表
        return securityReferences;
    }
}
